// Copyright (C) 2022 Huawei Device Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package controllers

import (
	"dist/model"
	"dist/services"
	"dist/utils"
	"fmt"
	"net/http"
)

func GeneralRecord(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		utils.Resp(w)(0, "success", map[string]interface{}{})
		return
	}
	var req model.GeneralRecordReq
	error := utils.RequestToStruct(r, &req)
	if error == nil {
		error = services.HandleGeneralRecord(req)
	}
	if error == nil {
		utils.Resp(w)(0, "success", map[string]interface{}{})
	} else {
		utils.Resp(w)(-1, "error", map[string]interface{}{})
	}
}

func GeneralQuery(w http.ResponseWriter, r *http.Request) {
	var req model.GeneralQueryReq
	if err := utils.RequestToStruct(r, &req); err != nil {
		utils.Resp(w)(-1, fmt.Sprintf("%v", err), map[string]interface{}{})
		return
	}
	if err := utils.CheckParameters(&req); err != nil {
		utils.Resp(w)(-1, fmt.Sprintf("%v", err), map[string]interface{}{})
		return
	}
	data := services.HandleGeneralQuery(req)
	if data == nil || len(data) == 0 {
		utils.Resp(w)(0, "data error", map[string]interface{}{
			"data": nil,
		})
	} else {
		utils.Resp(w)(0, "success", map[string]interface{}{
			"data": data,
		})
	}
}
